<?php 
namespace app\common\library;
use GuzzleHttp\Client;

class BtcPay{
    protected $config = [
        'client_id' => '',
        'base_url' => ''
    ];

    public function __construct($options = []){
        $this->config = array_merge(config('btcpay'), $options);
    }
    public function  getClient()
    {
        return new Client([
            'base_uri' => $this->config['base_url'],
            'timeout'  => 10.0,
            'verify' => false,
        ]);
    }

    public function encodeSign($data){
        // 1. 按ASCII从小到大排序
        ksort($data);
        // 2. 使用http_build_query自动拼接参数
        $queryString = http_build_query($data);
        $queryString = urldecode($queryString);
        
        // 3. 统一转换为小写并去除空格
        $queryString = strtolower(str_replace(' ', '', $queryString));
        
        // 4. 确保UTF-8编码
        $utf8String = mb_convert_encoding($queryString, 'UTF-8');
        
        // 5. SHA1哈希并转16进制小写
        return strtolower(sha1($utf8String));
    }

    public function createOrder($money, $name, $tradeNo, $notifyUrl){
        $data = [
            'name' => $name,
            'price' => $money,
            'client_order_id' => $tradeNo,
            'notify_url' => $notifyUrl,
            'client_id' => $this->config['client_id'],
        ];
        $data['sign'] = $this->encodeSign($data);
        $data = array_diff_key($data, ['key' => '']);
        var_dump($data);
        $response = $this->getClient()
            ->post('otctrade/bargain', [
                'headers' => [
                    'Content-Type' => 'application/json'
                ],
                'json' => $data
            ]);
        // $result = json_decode($response->getBody()->getContents(), true);
        var_dump($response->getBody()->getContents());
        return [];
        if($result['status'] !== 0){
            throw new \RuntimeException(''.$result['status']. ''.$result['reason']);
        }
        return $result['data'];
    }
}